package com.mateng.treasurechest.view.recipe.weight

import android.content.Context
import android.util.AttributeSet
import android.widget.LinearLayout
import android.widget.TextView
import com.bumptech.glide.Glide
import com.google.gson.Gson
import com.mateng.treasurechest.view.recipe.glideOptions
import org.json.JSONArray
import org.json.JSONException

/**
 * Created by mateng on 2018/1/27.
 */

class RecipeStepView : LinearLayout {

    private var methodBeans: ArrayList<MethodBean>? = null

    constructor(context: Context) : super(context) {}

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {}

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {}

    private fun refreshView() {
        methodBeans?.let {
            for (methodBean in it) {
                val recipeImageView = RecipeImageView(context)
                val layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)
                layoutParams.topMargin = 20
                recipeImageView.layoutParams = layoutParams
                Glide.with(this).applyDefaultRequestOptions(glideOptions).load(methodBean.img).into(recipeImageView)
                val recipeText = TextView(context)
                recipeText.text = methodBean.step
                addView(recipeImageView)
                addView(recipeText)
            }
        }
    }

    fun setData(method: String?) {
        methodBeans ?: let {
            methodBeans = ArrayList()
        }
        try {
            val array = JSONArray(method)
            (0 until array.length())
                    .map { Gson().fromJson(array.get(it).toString(), MethodBean::class.java) }
                    .forEach { methodBeans!!.add(it) }
        } catch (e: JSONException) {
            e.printStackTrace()
        }
        refreshView()

    }


    internal inner class MethodBean {
        /**
         * img : http://f2.mob.com/null/2015/08/19/1439945960062.jpg
         * step : 2.关火后将肉浸泡20分钟
         */
        var img: String? = null
        var step: String? = null
    }


}
